package com.koron.car.web.costregister.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.car.config.Constants;
import com.koron.car.web.carledger.bean.vo.CarVO;
import com.koron.car.web.carledger.mapper.CarMapper;
import com.koron.car.web.common.CommonUtils;
import com.koron.car.web.costregister.bean.entity.CostRegister;
import com.koron.car.web.costregister.bean.vo.CostRegisterExcel;
import com.koron.car.web.costregister.mapper.CostRegisterMapper;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class StorageListener implements ReadListener<CostRegisterExcel> {

    private SessionFactory factory;
    private static final List<CostRegister> LIST = new ArrayList<>();
    private static final int BATCH_COUNT = 50;

    public StorageListener(){
    }

    public StorageListener(SessionFactory factory){
        this.factory = factory;
    }


    @Override
    public void invoke(CostRegisterExcel costRegisterExcel, AnalysisContext analysisContext) {
        EamUser eamUser = ThreadLocalContext.get();
        String licPlateNum = costRegisterExcel.getLicPlateNum();
        CarMapper carMapper = factory.getMapper(CarMapper.class);
        CarVO carVO = carMapper.queryByPlateNum(licPlateNum);
        CostRegister costRegister = new CostRegister();
        if (Objects.nonNull(carVO)){
            costRegister.setMotorcade(carVO.getMotorcade() == null ? null : carVO.getMotorcade());
            costRegister.setCarId(carVO.getId());
        }
        CommonUtils.update(costRegister, eamUser);
        costRegister.setDeptId(eamUser.getOrgId());
        costRegister.setId(CodeTools.getCode32());
        costRegister.setCostType(Constants.FeeType.OILFEE);
        costRegister.setState(Constants.FeeState.FINISH);
        BeanUtil.copyProperties(costRegisterExcel,costRegister);
        LIST.add(costRegister);
        if (LIST.size()>=BATCH_COUNT){
            saveData(LIST);
            LIST.clear();
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(LIST.size()==0){
            return;
        }
        saveData(LIST);

        // 保存完之后清空集合数据
        if (LIST.size()>0){
            LIST.clear();
        }
    }

    private void saveData(List<CostRegister> list) {
        CostRegisterMapper costRegisterMapper = factory.getMapper(CostRegisterMapper.class);
        costRegisterMapper.insertBatch(list);
    }


}
